package org.csu.chatroom.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.chatroom.entity.Room;
import org.csu.chatroom.entity.User;
import org.csu.chatroom.persistence.RoomMapper;
import org.csu.chatroom.persistence.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ChatController {
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private UserMapper userMapper;
    // 跳转到聊天首页，显示用户信息和聊天室列表
    @GetMapping("/chat-home")
    public String chatHome(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");  // 从 Session 中获取用户信息
        if (user == null) {
            return "redirect:/login";  // 如果用户未登录，重定向到登录页面
        }

        model.addAttribute("user", user);  // 将用户信息传递给视图

        // 获取所有聊天室
        List<Room> rooms = roomMapper.selectList(null);
        model.addAttribute("rooms", rooms);

        return "chat-home";  // 返回聊天首页视图
    }

    @PostMapping("/create-room")
    public String createRoom(@RequestParam String name, HttpSession session) {
        User user = (User) session.getAttribute("user");  // 从 Session 获取用户信息
        if (user == null) {
            return "redirect:/login";  // 如果用户未登录，重定向到登录页面
        }

        // 创建新聊天室
        Room room = new Room();
        room.setName(name);
        roomMapper.insert(room);

        // 创建聊天室后跳转到该聊天室的界面
        return "login";
    }


}
